package com.kmxd.ams.core.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.kmxd.ams.core.common.bo.DictModel;
import com.kmxd.ams.core.common.constant.CacheConst;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 字典缓存工具类
 *
 * @author admin
 */
public class DictUtil {

  public static String getCacheKey(String key) {
    return CacheConst.CACHE_PREFIX_SYS_DICT + ":" + key;
  }

  public static List<DictModel> getDictList(String dictCode) {
    Object obj = SpringUtil.getBean(RedisUtils.class).get(getCacheKey(dictCode));
    return Objects.nonNull(obj) ? (List<DictModel>) obj : new ArrayList();
  }

  public static String getDictLabel(String dictCode, String dictValue) {
    if (StrUtil.isBlank(dictCode) || StrUtil.isBlank(dictValue)) {
      return "";
    }
    List<DictModel> dictModelList = getDictList(dictCode);
    DictModel dictModel =
        dictModelList.stream().filter(x -> x.getValue().equals(dictValue)).findFirst().orElse(null);
    return Objects.nonNull(dictModel) ? dictModel.getLabel() : "";
  }

  public static String getDictValue(String dictCode, String dictLabel) {
    if (StrUtil.isBlank(dictCode) || StrUtil.isBlank(dictLabel)) {
      return "";
    }
    List<DictModel> dictModelList = getDictList(dictCode);
    DictModel dictModel =
        dictModelList.stream().filter(x -> x.getLabel().equals(dictLabel)).findFirst().orElse(null);
    return Objects.nonNull(dictModel) ? dictModel.getValue().toString() : "";
  }

  public static void setDictCache(String dictCode, List<DictModel> dictModelList) {
    if (StrUtil.isBlank(dictCode) || Objects.isNull(dictModelList) || dictModelList.isEmpty()) {
      return;
    }
    SpringUtil.getBean(RedisUtils.class).set(getCacheKey(dictCode), dictModelList);
  }

  public static void clearDictCache() {
    Collection<String> keys = SpringUtil.getBean(RedisUtils.class).keys(getCacheKey("*"));
    SpringUtil.getBean(RedisUtils.class).del(keys.toArray(new String[0]));
  }
}
